<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 获取请求参数
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'rounds':
            // 获取历史轮次列表
            $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
            $filter = isset($_GET['filter']) ? $_GET['filter'] : 'today';
            $rounds = getHistoryRounds($limit, $filter);
            
            // 格式化轮次数据
            $formatted_rounds = [];
            foreach ($rounds as $round) {
                $formatted_rounds[] = [
                    'id' => $round['id'],
                    'round_number' => $round['round_number'],
                    'status' => $round['status'],
                    'status_text' => getRoundStatusText($round['status']),
                    'start_time' => $round['start_time'],
                    'end_time' => $round['end_time'],
                    'settlement_price' => $round['settlement_price'] ? number_format($round['settlement_price'], 2) : null,
                    'duration' => calculateRoundDuration($round['start_time'], $round['end_time'])
                ];
            }
            
            echo json_encode([
                'success' => true,
                'rounds' => $formatted_rounds
            ]);
            break;
            
        case 'kline':
            // 获取指定轮次的K线数据
            $round_id = isset($_GET['round']) ? intval($_GET['round']) : 0;
            
            if ($round_id <= 0) {
                echo json_encode(['success' => false, 'message' => '无效的轮次ID']);
                exit;
            }
            
            $kline_data = getRoundKlineData($round_id);
            
            if ($kline_data === null) {
                echo json_encode(['success' => false, 'message' => '轮次不存在']);
                exit;
            }
            
            // 获取交易统计
            $trading_stats = getRoundTradingStats($round_id);
            
            echo json_encode([
                'success' => true,
                'round' => $kline_data['round'],
                'kline_data' => $kline_data['kline_data'],
                'summary' => $kline_data['summary'],
                'trading_stats' => $trading_stats
            ]);
            break;
            
        case 'daily_kline':
            // 获取某天所有轮次的K线数据（每根K线代表一轮）
            $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
            
            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                echo json_encode(['success' => false, 'message' => '无效的日期格式']);
                exit;
            }
            
            $daily_kline_data = getDailyRoundsKlineData($date);
            
            echo json_encode([
                'success' => true,
                'date' => $daily_kline_data['date'],
                'kline_data' => $daily_kline_data['kline_data'],
                'summary' => $daily_kline_data['summary']
            ]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => '无效的操作']);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '获取数据失败: ' . $e->getMessage()
    ]);
}

// 辅助函数：计算轮次持续时间
function calculateRoundDuration($start_time, $end_time) {
    $start = strtotime($start_time);
    $end = strtotime($end_time);
    $duration = $end - $start;
    
    $minutes = floor($duration / 60);
    $seconds = $duration % 60;
    
    return $minutes . '分' . $seconds . '秒';
}
?>
